package kntc.backing;

import common.Utils;

import java.io.File;

import java.io.FileOutputStream;
import java.io.InputStream;

import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;

import javax.mail.MessagingException;

import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.WindowState;

import javax.servlet.http.HttpServletRequest;

import kntc.kntc;

import kntc.resource.kntcBundle;

import nl.captcha.Captcha;

import oracle.adf.model.binding.DCIteratorBinding;

import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.input.RichSelectOneRadio;

import oracle.adf.view.rich.component.rich.layout.RichPanelFormLayout;
import oracle.adf.view.rich.component.rich.output.RichOutputText;
import oracle.adf.view.rich.context.AdfFacesContext;

import org.apache.myfaces.trinidad.context.RequestContext;
import org.apache.myfaces.trinidad.model.UploadedFile;

import system.SystemSecurity;

import util.MailImplement;

public class kntcBacking {
    private String mPortletTitle;
    private UploadedFile _file;
    private String answer;
    private String langid;
    private String tieude;
    private String donthu = "1";
    private static String emailnoinhan;
    private String ketqua = "";

    private RichOutputText rotKetqua = new RichOutputText();
    private RichPanelFormLayout formlayout;
    private RichInputText txtHoten = new RichInputText();
    private RichInputText txtDiachi = new RichInputText();
    private RichInputText txtEmailnguoigui = new RichInputText();
    private RichInputText txtTieude = new RichInputText();
    private RichInputText txtNoidung = new RichInputText();
    
    public kntcBacking(){
        if (Boolean.FALSE.equals(Utils.getElExpression("#{adfFacesContext.postback}"))) {
            ketqua = "";
            rotKetqua.setVisible(false);
        }
    }

    private String getResource(String resourceKey) {
        Locale locale = getPortalLocale();
        ResourceBundle bundle =
            ResourceBundle.getBundle("portlet.PortletsBundle", locale);
        return bundle.getString(resourceKey);
    }

    public void beforePhase(PhaseEvent phaseEvent) {
        PortletRequest request =
            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        Integer reset =
            (Integer)request.getPortletSession().getAttribute("reset");
        if (reset != null && reset == 1) {
            request.getPortletSession().setAttribute("reset", 0);
            Utils.execute("Rollback");
            Utils.execute("CreateInsert");
        }
    }

    /**
     * Author       Date        Comment
     *  TớiNT    09/11/2012     Kiểm tra captcha
     * @return
     */
    public boolean capcha() {
        try {
            PortletRequest request =
                (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            HttpServletRequest httpServletRequest =
                (HttpServletRequest)request.getAttribute("javax.servlet.request");
            if (httpServletRequest != null) {
                Captcha captcha =
                    (Captcha)httpServletRequest.getSession().getAttribute(Captcha.NAME);
                if (captcha != null && this.getAnswer() != null) {
                    if (captcha.isCorrect(this.getAnswer())) {
                        return true;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    public boolean isPostback() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Application app = facesContext.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = facesContext.getELContext();
        ValueExpression valueExp =
            elFactory.createValueExpression(elContext, "#{requestContext.postback}",
                                            Object.class);
        Object postback = valueExp.getValue(elContext);
        if (postback != null) {
            return Boolean.TRUE.equals(valueExp.getValue(elContext));
        }
        return false;
    }

    public void Send(File file) {
        MailImplement mail = new MailImplement();
        String tieudemail = txtTieude.getValue().toString();
        String mailnguoigui = txtEmailnguoigui.getValue().toString();
        String noidungmail = txtNoidung.getValue().toString();
        String emailnhan = emailnoinhan;
        try {
            mail.sendEmail(emailnhan, tieudemail, noidungmail, mailnguoigui,
                           file);
        } catch (Exception mse) {
            mse.printStackTrace();
        }
    }

    public void Insert(ActionEvent actionEvent) {
        if (capcha()) {
            try {
                boolean fileupload = true;
                File filePath =
                    new File(Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"),
                             Utils.ENUM_CAU_HINH_KHOA.KNTC_DIR.getValue("HtCauHinhView1Iterator"));
                File duongdantuongdoi =
                    new File(Utils.ENUM_CAU_HINH_KHOA.KNTC_DIR.getValue("HtCauHinhView1Iterator"));
                //File filePath = new File("C:\\KNTC\\");
                UploadedFile file = this.getFile();
                File obj = null;
                FileOutputStream output = null;

                Object fileId = null;
                DCIteratorBinding fileIterator1 =
                    Utils.getIteratorBinding("HtFileView1Iterator");
                DCIteratorBinding IteratorKntc =
                    Utils.getIteratorBinding("KntcView1Iterator");
                IteratorKntc.getCurrentRow().setAttribute("NgayGui",
                                                          Utils.getCurrentDate().dateValue().toString());
                if (getDonthu() != null) {
                    IteratorKntc.getCurrentRow().setAttribute("LoaiKntc",
                                                              getDonthu());
                }
                if (file != null) {
                    String fileName = file.getFilename();
                    if (Utils.checkDefaultFileExtension(fileName)) {
                        try {
                            if (filePath.exists() == false) {
                                filePath.mkdirs();
                            }
                            byte buffer[] = new byte[1024];
                            int size = 0;
                            InputStream input = file.getInputStream();
                            Utils.execute("HtFileInsert");
                            fileId =
                                    fileIterator1.getCurrentRow().getAttribute("Id");
                            output =
                                    new FileOutputStream(new File(filePath, fileId +
                                                                  "_" +
                                                                  fileName));
                            while ((size = input.read(buffer)) != -1) {
                                output.write(buffer);
                            }
                            obj = new File(filePath, fileId + "_" + fileName);
                            Utils.processUpload(file, duongdantuongdoi,
                                                "HtFileView1Iterator",
                                                "KntcView1Iterator",
                                                Utils.ENUM_MA_UNG_DUNG.KNTC,
                                                fileId.toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (output != null) {
                                try {
                                    output.flush();
                                    output.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else {
                        this.setAnswer(null);
                        this.setFile(null);
                        ketqua =
                                "Hệ thống hỗ trợ file có định dạng: *.doc,*.docx,*.xls,*.xlsx,<br/>*.ppt,*.pptx,*.odt,*.ods,*.odp,*.pdf,*.zip,*.rar,*.txt";
                        rotKetqua.setInlineStyle("color:red;");
                        rotKetqua.setVisible(true);
                        PortletRequest request =
                            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
                        request.getPortletSession().setAttribute("unreset", 2);
                        fileupload = false;
                    }
                }
                if (fileupload) {
                    // Gọi hàm gửi mail đến nơi nhận
                    Send(obj);
                    List lst = Utils.execute("Commit");
                    if (lst == null) {
                        this.setFile(null);
                        this.setAnswer(null);
                        this.setDonthu("1");
                        Utils.iteratorRefresh("KntcView1Iterator");
                        Utils.execute("CreateInsert");
                        ketqua = "Gửi khiếu nại tố cáo thành công.";
                        rotKetqua.setInlineStyle("color:blue;");
                        rotKetqua.setVisible(true);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            if (this.getAnswer() != null) {
                ketqua = "Bạn nhập sai mã xác nhận. Yêu cầu nhập lại.";
                rotKetqua.setInlineStyle("color:red;");
                rotKetqua.setVisible(true);
                this.setAnswer(null);
                this.setFile(null);
            } else {
                ketqua = "Yêu cầu nhập mã xác nhận.";
                rotKetqua.setInlineStyle("color:red;");
                rotKetqua.setVisible(true);
                this.setFile(null);
            }
            PortletRequest request =
                (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            request.getPortletSession().setAttribute("unreset", 2);
        }
    }

    private Locale getPortalLocale() {
        Locale portalLocale = new Locale("vi", "VN");
        String language = "";
        try {
            PortletRequest request =
                (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            if (request.getParameter("ngonnguid") != null) {
                language = request.getParameter("ngonnguid");
                portalLocale = new Locale(language);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return portalLocale;
    }

    private String Tieude() {
        String tieudebieudo = "Gửi đơn thư";
        try {
            PortletRequest request =
                (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            if (request.getParameter("tieude") != null)
                tieudebieudo = request.getParameter("tieude").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return tieudebieudo;
    }

    //    private String getEmailnhan() {
    //        String email = "toint@tinhvan.com";
    //        try {
    //            PortletRequest request =
    //                (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    //            if (request.getParameter("email") != null)
    //                email = request.getParameter("email").toString();
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //        }
    //        return email;
    //    }

    public void setTieude(String tieude) {
        this.tieude = tieude;
    }

    public String getTieude() {
        tieude = Tieude();
        return tieude;
    }

    public void setFile(UploadedFile _file) {
        this._file = _file;
    }

    public UploadedFile getFile() {
        return _file;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    public String getAnswer() {
        return answer;
    }

    public void setLangid(String langid) {
        this.langid = langid;
    }

    public String getLangid() {
        langid = getPortalLocale().getLanguage();
        return langid;
    }

    public void setDonthu(String donthu) {
        this.donthu = donthu;
    }

    public String getDonthu() {
        return donthu;
    }

    public void setEmailnoinhan(String emailnoinhan) {
        this.emailnoinhan = emailnoinhan;
    }

    public String getEmailnoinhan() {
        emailnoinhan = "toint@tinhvan.com";
        try {
            PortletRequest request =
                (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            if (request.getParameter("email") != null)
                emailnoinhan = request.getParameter("email").toString();
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return emailnoinhan;
    }

    public void setTxtHoten(RichInputText txtHoten) {
        this.txtHoten = txtHoten;
    }

    public RichInputText getTxtHoten() {
        return txtHoten;
    }

    public void setTxtDiachi(RichInputText txtDiachi) {
        this.txtDiachi = txtDiachi;
    }

    public RichInputText getTxtDiachi() {
        return txtDiachi;
    }

    public void setTxtEmailnguoigui(RichInputText txtEmailnguoigui) {
        this.txtEmailnguoigui = txtEmailnguoigui;
    }

    public RichInputText getTxtEmailnguoigui() {
        return txtEmailnguoigui;
    }

    public void setTxtTieude(RichInputText txtTieude) {
        this.txtTieude = txtTieude;
    }

    public RichInputText getTxtTieude() {
        return txtTieude;
    }

    public void setTxtNoidung(RichInputText txtNoidung) {
        this.txtNoidung = txtNoidung;
    }

    public RichInputText getTxtNoidung() {
        return txtNoidung;
    }

    public void setFormlayout(RichPanelFormLayout formlayout) {
        this.formlayout = formlayout;
    }

    public RichPanelFormLayout getFormlayout() {
        return formlayout;
    }

    public void setKetqua(String ketqua) {
        this.ketqua = ketqua;
    }

    public String getKetqua() {
        return ketqua;
    }

    public void setRotKetqua(RichOutputText rotKetqua) {
        this.rotKetqua = rotKetqua;
    }

    public RichOutputText getRotKetqua() {
        return rotKetqua;
    }


    public String getHoVaTenLabel() {
        String resource = getResource("HO_TEN");
        return resource;
    }

    public String getNhapHoVaTen() {
        String resource = getResource("NHAP_HO_VA_TEN");
        return resource;
    }

    public String getDiachilable() {
        String resource = getResource("DIA_CHI");
        return resource;
    }

    public String getDienthoaiLable() {
        String resource = getResource("DIEN_THOAI");
        return resource;
    }

    public String getEmail() {
        String resource = getResource("EMAIL");
        return resource;
    }

    public String getNhapDiaChiMail() {
        String resource = getResource("NHAP_DIA_CHI_MAIL");
        return resource;
    }

    public String getNhapSaiDinhDangMail() {
        String resource = getResource("NHAP_SAI_DINH_DANG_MAIL");
        return resource;
    }

    public String getTieuDeLabel() {
        String resource = getResource("TIEU_DE");
        return resource;
    }

    public String getNhaptieude() {
        String resource = getResource("NHAP_TIEU_DE");
        return resource;
    }

    public String getNoiDungkhieunaiLabel() {
        String resource = getResource("NOI_DUNG_KHIEU_NAI");
        return resource;
    }

    public String getNhapNoiDung() {
        String resource = getResource("NHAP_NOI_DUNG");
        return resource;
    }

    public String getNhapDiaChi() {
        String resource = getResource("NHAP_DIA_CHI_NOI_O");
        return resource;
    }

    public String getGuiKNTCButton() {
        String resource = getResource("GUI_KNTC");
        return resource;
    }

    public String getChonfileLabel() {
        String resource = getResource("FILE_DINH_KEM");
        return resource;
    }

    public String getMaxacnhanLabel() {
        String resource = getResource("MA_XAC_NHAN");
        return resource;
    }

    public String getDoiMaKhac() {
        String resource = getResource("DOI_MA_KHAC");
        return resource;
    }

    public String getChondonLable() {
        String resource = getResource("CHON_DON");
        return resource;
    }

    public String getKhieunaiLable() {
        String resource = getResource("DON_THU_KHIEU_NAI");
        return resource;
    }

    public String getTocaoLable() {
        String resource = getResource("DON_THU_TO_CAO");
        return resource;
    }
}
